/***************************************************************************
 * The Open Armory API is a project to retrieve World of Warcraft(R) 
 * related XML data from The Armory.
 * 
 * The data retrieved via the Open Armory API from The Armory is 
 * proprietary to Blizzard Entertainment, Inc(R).
 * *************************************************************************
 * Copyright (C) 2009 - 2010 Tedla M.B. Brandsema
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ***************************************************************************/
package net.openarmory.core.domain;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

/**
 * The Class {@code ArmoryBinaryWriter} is responsible for writing binary data
 * retrieved from The Armory to disk.
 */
class ArmoryBinaryWriter {

	/** The log. */
	private static final Logger LOG = Logger
			.getLogger(ArmoryBinaryWriter.class);

	/**
	 * Write online resource to the file system.
	 * 
	 * @param contentLength
	 *            The content length in bytes.
	 * @param binaryStream
	 *            The {@code InputStream} containing the binary data.
	 * @param outFile
	 *            The output file.
	 */
	public final void writeBinaryFile(final int contentLength,
			final InputStream binaryStream, final File outFile) {

		try {
			final int length = contentLength;
			final byte[] bytes = new byte[length];

			int offset = 0;
			int numRead = 0;
			while ((offset < bytes.length)
					&& ((numRead = binaryStream.read(bytes, offset,
							bytes.length - offset)) >= 0)) {
				offset += numRead;
			}

			if (offset < bytes.length) {
				throw new IOException(
						"Could not completely read the InputStream.");
			}

			binaryStream.close();

			FileUtils.writeByteArrayToFile(outFile, bytes);
			LOG.info("File has been written to: " + outFile.getAbsolutePath());
		} catch (final FileNotFoundException e) {
			LOG.error("File not found exception", e);
		} catch (final IOException e) {
			LOG.error("IOException", e);
		}
	}
}
